package com.yaoxun.console.service;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.yaoxun.console.constant.CacheConstant;
import com.yaoxun.console.constant.GlobalConstant;
import com.yaoxun.console.exception.ValidatorException;
import com.yaoxun.console.util.CookieUtils;
import com.yaoxun.console.util.IdUtils;
import com.yaoxun.console.xo.dto.LoginSession;
import com.yaoxun.console.xo.entity.LoginUser;
import com.yaoxun.console.xo.req.LoginReq;
import com.yaoxun.console.xo.resp.LoginResp;

@Service
public class LoginService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private JsonService jsonService;
	
	private static final int MAX_AGE = 2 * 60 * 60;
	
	public LoginResp login(LoginReq req, HttpServletResponse response) {
		
		String value = (String) stringRedisTemplate.opsForHash().get(CacheConstant.LOGIN_USERS, req.getLoginName());
		
		if(value == null) {
			throw new ValidatorException("账号或密码错误");
		}
		
		LoginUser user = jsonService.parse(value, LoginUser.class);
		
		if(!req.getPassword().equals(user.getPassword())) {
			throw new ValidatorException("账号或密码错误");			
		}
		
		String sid = IdUtils.uuid();
		
		LoginSession session = new LoginSession();
		session.setLoginName(req.getLoginName());
		session.setSid(sid);
		
		String jsonSession = jsonService.toJsonString(session);
		
		String sessionKey = String.format(CacheConstant.LOGIN_SESSION, sid);
		
		stringRedisTemplate.opsForValue().set(sessionKey, jsonSession, MAX_AGE, TimeUnit.SECONDS);
		
		addCookie(response, GlobalConstant.SID_NAME, sid);
		
		LoginResp resp = new LoginResp();
		resp.setLoginName(req.getLoginName());
		
		return resp;
	}
	
	public LoginSession getSession(HttpServletRequest request) {
		
		String sidVal = CookieUtils.get(request, GlobalConstant.SID_NAME);
		
		if(StringUtils.isBlank(sidVal)) {
			return null;
		}
		
		String loginSessionKey = String.format(CacheConstant.LOGIN_SESSION, sidVal);
		
		String session = stringRedisTemplate.opsForValue().get(loginSessionKey);
		
		if(session == null) {
			return null;
		}
		
		return jsonService.parse(session, LoginSession.class);
	}
	
	
	public void refreshSession(HttpServletResponse response, LoginSession session) {
		
		String sessionKey = String.format(CacheConstant.LOGIN_SESSION, session.getSid());

		stringRedisTemplate.expire(sessionKey, MAX_AGE, TimeUnit.SECONDS);
		
		addCookie(response, GlobalConstant.SID_NAME, session.getSid());
	}
	
	public void addCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(MAX_AGE);
		response.addCookie(cookie);
	}
	
}
